﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BotvaBot.Configuration;
using HttpRequester.RequestMakers.Base;
using System.Net;
using HttpRequester;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using mshtml;
using Helpers;
using Helpers.Extensions;
using BotvaBot.RequestChains;
using BotvaBot.Configuration.Personaj;
using System.Threading;
using BotvaBot.RequestChainItems.Base;
using System.Reflection;
using HAP = HtmlAgilityPack;
using Common.Constants;
using HtmlParsing;
using BotvaBot.RequestChainItems;
using BotvaBot.Processor;
using System.Linq.Expressions;
using BotvaBot.RequestChains.Base;

namespace BotvaBot
{
    public partial class TestCommandsForm : Form
    {
        protected PersonajCfg CurrentPersonaj { get { return cmbPersonaj.SelectedItem as PersonajCfg; } }

        #region Context

        protected BotvaChainContext Context { get; set; }
        
        [Obsolete]
        protected Dictionary<string, Cookie> Cookies { get; set; }
        
        [Obsolete]
        protected string Content { get; set; }

        [Obsolete]
        protected void AddReturnedCookies(RequestManagerPlaneHtml rm)
        {
            if (CollectionHelper.IsNullOrEmpty(rm.OutputCookies))
                return;

            rm.OutputCookies.ForEach(cookie => Cookies.AddOrReset(cookie.Name, cookie));
        }

        #endregion Context



        public TestCommandsForm()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            cmbPersonaj.DisplayMember = "Name";
            cmbPersonaj.DataSource = Config.Custom.PersonajSet.Items;

            txtHeaders.Text = string.Empty;
            txtCoockie.Text = string.Empty;
            txtContent.Text = string.Empty;

            cmbWorkHours.DataSource = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
        }



        private void btnEnter_Click(object sender, EventArgs e)
        {
            EnterChainItem chi = new EnterChainItem();
            MakeRequest1(chi, false);
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            LoginChainItem chi = new LoginChainItem();
            MakeRequest1(chi, true);
        }


        private void btnLogout_Click(object sender, EventArgs e)
        {
            LogoutChainItem chi = new LogoutChainItem();
            MakeRequest1(chi, true);
        }


        private void btnGavan_Click(object sender, EventArgs e)
        {
            GotoGavanChainItem chi = new GotoGavanChainItem();
            MakeRequest1(chi, true);
        }

        private void btnPrichal_Click(object sender, EventArgs e)
        {
            GotoPrichalChainItem chi = new GotoPrichalChainItem();
            MakeRequest1(chi, true);
        }

        private void btnOtpravit_Click(object sender, EventArgs e)
        {
            SendBoatChainItem chi = new SendBoatChainItem();
            MakeRequest1(chi, true);
        }

        private void btnShahta_Click(object sender, EventArgs e)
        {
            GotoShahtaChainItem chi = new GotoShahtaChainItem();
            MakeRequest1(chi, true);

            #region OLD
            //RequestManagerPlaneHtml rm = new RequestManagerPlaneHtml();
            //rm.Url = "http://g3.botva.ru/mine.php";
            //rm.ContentType = HttpContentType.APPLICATION_X_WWW_FORM_URLENCODED;
            //rm.Method = HttpMethod.GET;

            //MakeRequest(rm);
	        #endregion
        }

        private void btnKarier_Click(object sender, EventArgs e)
        {
            GotoKarierChainItem chi = new GotoKarierChainItem();
            MakeRequest1(chi, true);

            #region OLD
            //RequestManagerPlaneHtml rm = new RequestManagerPlaneHtml();
            //rm.Url = "http://g3.botva.ru//mine.php?a=open";
            //rm.ContentType = HttpContentType.APPLICATION_X_WWW_FORM_URLENCODED;
            //rm.Method = HttpMethod.GET;

            //MakeRequest(rm); 
            #endregion
        }

        private void btnRabotat_Click(object sender, EventArgs e)
        {
            WorkInKarierChainItem chi = new WorkInKarierChainItem();
            MakeRequest1(chi, true);

            #region OLD
            //RequestManagerPlaneHtml rm = new RequestManagerPlaneHtml();
            //rm.Url = "http://g3.botva.ru";
            //rm.ContentType = HttpContentType.APPLICATION_X_WWW_FORM_URLENCODED;
            //rm.Method = HttpMethod.GET;
            ////rm.AddGet("a", "pier");

            //string content = Content;
            ////string content = FileHelper.GetContent("H:\\3.txt.html");

            //content = content.Replace(Environment.NewLine, string.Empty);
            //while (content.IndexOf("  ") >= 0)
            //{
            //    content = content.Replace("  ", " ");
            //}
            //content = content.ToUpper();

            //IHTMLDocument2 html = new HTMLDocumentClass();
            //html.write(content);
            //html.close();

            //IHTMLElementCollection all = html.body.all as IHTMLElementCollection;
            //IHTMLElementCollection ahrefs = all.tags("A") as IHTMLElementCollection;


            ////string s = "";
            //foreach (IHTMLElement item in ahrefs)
            //{
            //    if (item.innerText != "РАБОТАТЬ")
            //        continue;

            //    IHTMLAnchorElement ahref = item as IHTMLAnchorElement;

            //    string address = ahref.pathname;
            //    if (!string.IsNullOrEmpty(address))
            //        rm.Url += "/" + address.ToLower();

            //    string queryString = ahref.search;
            //    if (queryString.StartsWith("?"))
            //        queryString = queryString.Substring("?".Length);
            //    string[] parameters = queryString.Split('&');
            //    foreach (string param in parameters)
            //    {
            //        string[] paramParts = param.Split('=');
            //        if (paramParts.Length >= 2)
            //        {
            //            rm.AddGet(paramParts[0].ToLower(), paramParts[1].ToLower());
            //        }
            //        else
            //        {
            //            rm.AddGet(paramParts[0].ToLower(), string.Empty);
            //        }
            //    }

            //    break;
            //}

            ////rm.AddPost("submit", "ОТПРАВИТЬ");

            //////txtContent.Text = s;

            //MakeRequest(rm); 
            #endregion
        }

        private void btnDobyt_Click(object sender, EventArgs e)
        {
            TryGetCristalChainItem chi = new TryGetCristalChainItem();
            MakeRequest1(chi, true);

            #region OLD
            //RequestManagerPlaneHtml rm = new RequestManagerPlaneHtml();
            //rm.Url = "http://g3.botva.ru";
            //rm.ContentType = HttpContentType.APPLICATION_X_WWW_FORM_URLENCODED;
            //rm.Method = HttpMethod.GET;
            ////rm.AddGet("a", "pier");

            //string content = Content;
            ////string content = FileHelper.GetContent("H:\\3.txt.html");

            //content = content.Replace(Environment.NewLine, string.Empty);
            //while (content.IndexOf("  ") >= 0)
            //{
            //    content = content.Replace("  ", " ");
            //}
            //content = content.ToUpper();

            //IHTMLDocument2 html = new HTMLDocumentClass();
            //html.write(content);
            //html.close();

            //IHTMLElementCollection all = html.body.all as IHTMLElementCollection;
            //IHTMLElementCollection ahrefs = all.tags("A") as IHTMLElementCollection;


            ////string s = "";
            //foreach (IHTMLElement item in ahrefs)
            //{
            //    if (item.innerText != "ДОБЫТЬ КРИСТАЛЛ")
            //        continue;

            //    IHTMLAnchorElement ahref = item as IHTMLAnchorElement;

            //    string address = ahref.pathname;
            //    if (!string.IsNullOrEmpty(address))
            //        rm.Url += "/" + address.ToLower();

            //    string queryString = ahref.search;
            //    if (queryString.StartsWith("?"))
            //        queryString = queryString.Substring("?".Length);
            //    string[] parameters = queryString.Split('&');
            //    foreach (string param in parameters)
            //    {
            //        string[] paramParts = param.Split('=');
            //        if (paramParts.Length >= 2)
            //        {
            //            rm.AddGet(paramParts[0].ToLower(), paramParts[1].ToLower());
            //        }
            //        else
            //        {
            //            rm.AddGet(paramParts[0].ToLower(), string.Empty);
            //        }
            //    }

            //    break;
            //}

            ////rm.AddPost("submit", "ОТПРАВИТЬ");

            //////txtContent.Text = s;

            //MakeRequest(rm); 
            #endregion
        }

        private void btnIskat_Click(object sender, EventArgs e)
        {
            WorkInKarierAgaineChainItem chi = new WorkInKarierAgaineChainItem();
            MakeRequest1(chi, true);

            #region OLD
            //RequestManagerPlaneHtml rm = new RequestManagerPlaneHtml();
            //rm.Url = "http://g3.botva.ru";
            //rm.ContentType = HttpContentType.APPLICATION_X_WWW_FORM_URLENCODED;
            //rm.Method = HttpMethod.GET;
            ////rm.AddGet("a", "pier");

            //string content = Content;
            ////string content = FileHelper.GetContent("H:\\3.txt.html");

            //content = content.Replace(Environment.NewLine, string.Empty);
            //while (content.IndexOf("  ") >= 0)
            //{
            //    content = content.Replace("  ", " ");
            //}
            //content = content.ToUpper();

            //IHTMLDocument2 html = new HTMLDocumentClass();
            //html.write(content);
            //html.close();

            //IHTMLElementCollection all = html.body.all as IHTMLElementCollection;
            //IHTMLElementCollection ahrefs = all.tags("A") as IHTMLElementCollection;


            ////string s = "";
            //foreach (IHTMLElement item in ahrefs)
            //{
            //    if (item.innerText != "ИСКАТЬ ДАЛЬШЕ")
            //        continue;

            //    IHTMLAnchorElement ahref = item as IHTMLAnchorElement;

            //    string address = ahref.pathname;
            //    if (!string.IsNullOrEmpty(address))
            //        rm.Url += "/" + address.ToLower();

            //    string queryString = ahref.search;
            //    if (queryString.StartsWith("?"))
            //        queryString = queryString.Substring("?".Length);
            //    string[] parameters = queryString.Split('&');
            //    foreach (string param in parameters)
            //    {
            //        string[] paramParts = param.Split('=');
            //        if (paramParts.Length >= 2)
            //        {
            //            rm.AddGet(paramParts[0].ToLower(), paramParts[1].ToLower());
            //        }
            //        else
            //        {
            //            rm.AddGet(paramParts[0].ToLower(), string.Empty);
            //        }
            //    }

            //    break;
            //}

            ////rm.AddPost("submit", "ОТПРАВИТЬ");

            //////txtContent.Text = s;

            //MakeRequest(rm); 
            #endregion
        }

        private void btnUyti_Click(object sender, EventArgs e)
        {
            UytiFromShahtaChainItem chi = new UytiFromShahtaChainItem();
            MakeRequest1(chi, true);

            #region OLD
            //RequestManagerPlaneHtml rm = new RequestManagerPlaneHtml();
            //rm.Url = "http://g3.botva.ru";
            //rm.ContentType = HttpContentType.APPLICATION_X_WWW_FORM_URLENCODED;
            //rm.Method = HttpMethod.GET;
            ////rm.AddGet("a", "pier");

            //string content = Content;
            ////string content = FileHelper.GetContent("H:\\3.txt.html");

            //content = content.Replace(Environment.NewLine, string.Empty);
            //while (content.IndexOf("  ") >= 0)
            //{
            //    content = content.Replace("  ", " ");
            //}
            //content = content.ToUpper();

            //IHTMLDocument2 html = new HTMLDocumentClass();
            //html.write(content);
            //html.close();

            //IHTMLElementCollection all = html.body.all as IHTMLElementCollection;
            //IHTMLElementCollection ahrefs = all.tags("A") as IHTMLElementCollection;


            ////string s = "";
            //foreach (IHTMLElement item in ahrefs)
            //{
            //    if (item.innerText != "УЙТИ С ШАХТЫ")
            //        continue;

            //    IHTMLAnchorElement ahref = item as IHTMLAnchorElement;

            //    string address = ahref.pathname;
            //    if (!string.IsNullOrEmpty(address))
            //        rm.Url += "/" + address.ToLower();

            //    string queryString = ahref.search;
            //    if (queryString.StartsWith("?"))
            //        queryString = queryString.Substring("?".Length);
            //    string[] parameters = queryString.Split('&');
            //    foreach (string param in parameters)
            //    {
            //        string[] paramParts = param.Split('=');
            //        if (paramParts.Length >= 2)
            //        {
            //            rm.AddGet(paramParts[0].ToLower(), paramParts[1].ToLower());
            //        }
            //        else
            //        {
            //            rm.AddGet(paramParts[0].ToLower(), string.Empty);
            //        }
            //    }

            //    break;
            //}

            //MakeRequest(rm); 
            #endregion
        }

        private void btnDerevnya_Click(object sender, EventArgs e)
        {
            GotoDerevnyaChainItem chi = new GotoDerevnyaChainItem();
            MakeRequest1(chi, true);

            #region OLD
            //RequestManagerPlaneHtml rm = new RequestManagerPlaneHtml();
            //rm.Url = "http://g3.botva.ru/village.php";
            //rm.ContentType = HttpContentType.APPLICATION_X_WWW_FORM_URLENCODED;
            //rm.Method = HttpMethod.GET;

            //MakeRequest(rm); 
            #endregion
        }

        private void btnFerma_Click(object sender, EventArgs e)
        {
            GotoDerevnyaChainItem chi = new GotoDerevnyaChainItem();
            MakeRequest1(chi, true);

            #region OLD
            //RequestManagerPlaneHtml rm = new RequestManagerPlaneHtml();
            //rm.Url = "http://g3.botva.ru/farm.php";
            //rm.ContentType = HttpContentType.APPLICATION_X_WWW_FORM_URLENCODED;
            //rm.Method = HttpMethod.GET;

            //MakeRequest(rm); 
            #endregion
        }

        private void btnWork_Click(object sender, EventArgs e)
        {
            WorkInKarierChainItem chi = new WorkInKarierChainItem();
            MakeRequest1(chi, true);
            
            #region OLD
            //RequestManagerPlaneHtml rm = new RequestManagerPlaneHtml();
            //rm.Url = "http://g3.botva.ru/farm.php";
            //rm.ContentType = HttpContentType.APPLICATION_X_WWW_FORM_URLENCODED;
            //rm.Method = HttpMethod.POST;

            //string content = Content;

            //content = content.Replace(Environment.NewLine, string.Empty);
            //while (content.IndexOf("  ") >= 0)
            //{
            //    content = content.Replace("  ", " ");
            //}
            //content = content.ToUpper();

            //IHTMLDocument2 html = new HTMLDocumentClass();
            //html.write(content);
            //html.close();

            //IHTMLElementCollection all = html.body.all as IHTMLElementCollection;

            //IHTMLElementCollection inputs = all.tags("INPUT") as IHTMLElementCollection;
            //foreach (IHTMLElement item in inputs)
            //{
            //    IHTMLInputHiddenElement inputHidden = item as IHTMLInputHiddenElement;
            //    if (inputHidden == null)
            //        continue;

            //    if (inputHidden.name == "K")
            //    {
            //        rm.AddPost(inputHidden.name.ToLower(), inputHidden.value.ToLower());
            //        break;
            //    }

            //    //if (inputHidden.name == "CMD")
            //    //    rm.AddPost(inputHidden.name.ToLower(), inputHidden.value.ToLower());
            //}

            //int hours = cmbWorkHours.SelectedItem != null ? (int)cmbWorkHours.SelectedItem : 1;
            //rm.AddPost("work", hours.ToString());

            //rm.AddPost("cmd", "do");

            ////IHTMLElementCollection selects = all.tags("SELECT") as IHTMLElementCollection;
            ////foreach (IHTMLElement item in inputs)
            ////{
            ////    IHTMLSelectElement select = item as IHTMLSelectElement;

            ////    if (select == null)
            ////        continue;

            ////    if (select.name == "WORK")
            ////    {
            ////        select.value;
            ////    }
            ////}

            //MakeRequest(rm); 
            #endregion
        }

        private void btnOtmenit_Click(object sender, EventArgs e)
        {
            OtmenitWorkOnFermaChainItem chi = new OtmenitWorkOnFermaChainItem();
            MakeRequest1(chi, true);

            #region OLD
            //RequestManagerPlaneHtml rm = new RequestManagerPlaneHtml();
            //rm.Url = "http://g3.botva.ru/farm.php";
            //rm.ContentType = HttpContentType.APPLICATION_X_WWW_FORM_URLENCODED;
            //rm.Method = HttpMethod.POST;

            //string content = Content;

            //content = content.Replace(Environment.NewLine, string.Empty);
            //while (content.IndexOf("  ") >= 0)
            //{
            //    content = content.Replace("  ", " ");
            //}
            //content = content.ToUpper();

            //IHTMLDocument2 html = new HTMLDocumentClass();
            //html.write(content);
            //html.close();

            //IHTMLElementCollection all = html.body.all as IHTMLElementCollection;

            //IHTMLElementCollection inputs = all.tags("INPUT") as IHTMLElementCollection;
            //foreach (IHTMLElement item in inputs)
            //{
            //    IHTMLInputHiddenElement inputHidden = item as IHTMLInputHiddenElement;
            //    if (inputHidden == null)
            //        continue;

            //    if (inputHidden.name == "K")
            //    {
            //        rm.AddPost(inputHidden.name.ToLower(), inputHidden.value.ToLower());
            //        break;
            //    }

            //    //if (inputHidden.name == "CMD")
            //    //    rm.AddPost(inputHidden.name.ToLower(), inputHidden.value.ToLower());
            //}

            //rm.AddPost("cmd", "cancel");

            //MakeRequest(rm); 
            #endregion
        }


        #region NEW ENGINE

        protected void MakeRequest1(ExtendedChainItenBase item, bool withInheritedContext)
        {
            bool IsSuccessfulyInvoked = true;

            if (!withInheritedContext)
            {
                Context = new BotvaChainContext();
            }

            Context.Personaj = CurrentPersonaj;

            //string LastContent = null;
            //if (withInheritedContext)
            //    LastContent = Context.LastResponseContent;

            try
            {
                bool ProcessFlag = true;

                if (withInheritedContext)
                {
                    item.Chain = new BotvaChainBase(Context);
                    item.Chain.LastContent = Context.PreviousResponseContent;
                    item.Chain.Personaj = Context.Personaj;
                }
                else
                    item.Chain = new BotvaChainBase();


                ProcessFlag = item.IsContextValid();
                if (!ProcessFlag)
                    throw new ChainInvokationIsFailedException("Context is Not Valid");

                try
                {
                    item.PrepareRequest();
                }
                catch (Exception ex)
                {
                    throw new ChainInvokationIsFailedException("Request prepearing was failed", ex);
                }

                ProcessFlag = item.IsRequestValid();
                if (!ProcessFlag)
                    throw new ChainInvokationIsFailedException("Request is Not Valid");

                try
                {
                    item.DoRequest();
                }
                catch (Exception ex)
                {
                    throw new ChainInvokationIsFailedException("Request was done with problems", ex);
                }

                ProcessFlag = item.IsResponseValid();
                if (!ProcessFlag)
                    throw new ChainInvokationIsFailedException("Response is Not Valid");

                try
                {
                    item.UpdateContext();
                }
                catch (Exception ex)
                {
                    throw new ChainInvokationIsFailedException("Context Update was not done correct", ex);
                }

                item.ProcessFlag = ProcessFlag;
                
                Context = new BotvaChainContext(item.Chain.Context);
                Context.PreviousResponseContent = item.ResponseContent;
                
                IsSuccessfulyInvoked = true;
            }
            catch (ChainInvokationIsFailedException ex)
            {
                MessageBox.Show(ex.Message);
                IsSuccessfulyInvoked = false;
            }

            MessageBox.Show(IsSuccessfulyInvoked.ToString().ToUpper());

            if (IsSuccessfulyInvoked)
            {
                RequestManagerPlaneHtml rm = item.Requester;
                ShowResponse1(rm);
            }
            else
            {
                // Clear results
                //ClearResponse1();
            }
        }

        protected void ShowResponse1(RequestManagerPlaneHtml rm)
        {
            StringBuilder sb = new StringBuilder();
            if (!CollectionHelper.IsNullOrEmpty(rm.OutputCookies))
            {
                rm.OutputCookies.ForEach(c =>
                {
                    sb.AppendLine("Name : " + c.Name);
                    sb.AppendLine("Value : " + c.Value);
                    sb.AppendLine("Domain : " + c.Domain);
                    sb.AppendLine("Discard : " + c.Discard);
                    sb.AppendLine("Expires : " + c.Expires.ToLongDateString() + " " + c.Expires.ToLongTimeString());
                    sb.AppendLine("Expired : " + c.Expired.ToString());
                    sb.AppendLine("HttpOnly : " + c.HttpOnly.ToString());
                    sb.AppendLine("Path : " + c.Path);
                    sb.AppendLine("Port : " + c.Port);
                    sb.AppendLine("Secure : " + c.Secure.ToString());
                    sb.AppendLine("TimeStamp : " + c.TimeStamp.ToLongDateString() + " " + c.TimeStamp.ToLongTimeString());
                    sb.AppendLine("Version : " + c.Version);
                    sb.AppendLine("Comment : " + c.Comment);
                    sb.AppendLine("CommentUri : " + c.CommentUri);
                    sb.AppendLine("-----------------------------------------------------------");
                    sb.AppendLine();
                });
            }
            txtCoockie.Text = sb.ToString();

            sb = new StringBuilder();
            if (!CollectionHelper.IsNullOrEmpty(rm.Response.Headers))
            {
                foreach (string name in rm.Response.Headers.AllKeys)
                {
                    sb.AppendLine(name + " : " + rm.Response.Headers[name]);
                }
            }
            txtHeaders.Text = sb.ToString();

            txtContent.Text = rm.PageContent;
        }

        protected void ClearResponse1()
        {
            txtCoockie.Text = string.Empty;
            txtHeaders.Text = string.Empty;
            txtContent.Text = string.Empty;
        }

        #endregion NEW ENGINE



        #region OLD ENGINE

        [Obsolete]
        protected void MakeRequest(RequestManagerPlaneHtml rm)
        {
            //request.Proxy = new WebProxy("localhost:8192");

            rm.Context.AddWellknownHeaders(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 ( .NET CLR 3.5.30729; .NET4.0E)");
            rm.Context.AddWellknownHeaders(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            rm.Context.AddWellknownHeaders(HttpRequestHeader.Connection, "Keep-Alive");
            rm.Context.AddWellknownHeaders(HttpRequestHeader.AcceptLanguage, "ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3");
            rm.Context.AddWellknownHeaders(HttpRequestHeader.AcceptCharset, "windows-1251,utf-8;q=0.7,*;q=0.7");

            rm.Context.AddCustomHeader("Keep-Alive", "115");

            rm.Context.LoadInputCookies(Cookies.Values.ToList());

            rm.DoRequest();

            AddReturnedCookies(rm);

            //Content = rm.PageContent;

            ShowResponse(rm);
        }

        [Obsolete]
        protected void ShowResponse(RequestManagerPlaneHtml rm)
        {
            StringBuilder sb = new StringBuilder();
            if (!CollectionHelper.IsNullOrEmpty(rm.OutputCookies))
            {
                rm.OutputCookies.ForEach(c =>
                {
                    sb.AppendLine("Name : " + c.Name);
                    sb.AppendLine("Value : " + c.Value);
                    sb.AppendLine("Domain : " + c.Domain);
                    sb.AppendLine("Discard : " + c.Discard);
                    sb.AppendLine("Expires : " + c.Expires.ToLongDateString() + " " + c.Expires.ToLongTimeString());
                    sb.AppendLine("Expired : " + c.Expired.ToString());
                    sb.AppendLine("HttpOnly : " + c.HttpOnly.ToString());
                    sb.AppendLine("Path : " + c.Path);
                    sb.AppendLine("Port : " + c.Port);
                    sb.AppendLine("Secure : " + c.Secure.ToString());
                    sb.AppendLine("TimeStamp : " + c.TimeStamp.ToLongDateString() + " " + c.TimeStamp.ToLongTimeString());
                    sb.AppendLine("Version : " + c.Version);
                    sb.AppendLine("Comment : " + c.Comment);
                    sb.AppendLine("CommentUri : " + c.CommentUri);
                    sb.AppendLine("-----------------------------------------------------------");
                    sb.AppendLine();
                });
            }
            txtCoockie.Text = sb.ToString();

            sb = new StringBuilder();
            if (!CollectionHelper.IsNullOrEmpty(rm.Response.Headers))
            {
                foreach (string name in rm.Response.Headers.AllKeys)
                {
                    sb.AppendLine(name + " : " + rm.Response.Headers[name]);
                }
            }
            txtHeaders.Text = sb.ToString();

            txtContent.Text = rm.PageContent;
        }


        #endregion OLD ENGINE





        #region Get Personaj Info

        private void btnMoney_Click(object sender, EventArgs e)
        {
            PersonajCfg personaj = cmbPersonaj.SelectedItem as PersonajCfg;
            int value = new PersonajInfo(personaj).GetMoney();
            lbValue.Text = value.ToString();
        }

        private void btnKristaly_Click(object sender, EventArgs e)
        {
            PersonajCfg personaj = cmbPersonaj.SelectedItem as PersonajCfg;
            int value = new PersonajInfo(personaj).GetKristaly();
            lbValue.Text = value.ToString();
        }

        private void btnPirashki_Click(object sender, EventArgs e)
        {
            PersonajCfg personaj = cmbPersonaj.SelectedItem as PersonajCfg;
            int value = new PersonajInfo(personaj).GetPirashki();
            lbValue.Text = value.ToString();
        }

        private void btnKapusta_Click(object sender, EventArgs e)
        {
            PersonajCfg personaj = cmbPersonaj.SelectedItem as PersonajCfg;
            int value = new PersonajInfo(personaj).GetKapusta();
            lbValue.Text = value.ToString();
        }

        private void btnKirka_Click(object sender, EventArgs e)
        {
            PersonajCfg personaj = cmbPersonaj.SelectedItem as PersonajCfg;
            int value = new PersonajInfo(personaj).GetKirka();
            lbValue.Text = value.ToString();
        }

        private void btnKaska_Click(object sender, EventArgs e)
        {
            PersonajCfg personaj = cmbPersonaj.SelectedItem as PersonajCfg;
            int value = new PersonajInfo(personaj).GetKaska();
            lbValue.Text = value.ToString();
        }

        private void btnOchki_Click(object sender, EventArgs e)
        {
            PersonajCfg personaj = cmbPersonaj.SelectedItem as PersonajCfg;
            int value = new PersonajInfo(personaj).GetOchki();
            lbValue.Text = value.ToString();
        }

        private void btnZdorovie_Click(object sender, EventArgs e)
        {
            PersonajCfg personaj = cmbPersonaj.SelectedItem as PersonajCfg;
            //int value = new PersonajInfo(personaj).GetZdorovieCurrent();
            //int max = new PersonajInfo(personaj).GetZdorovieMax();
            string value = new PersonajInfo(personaj).GetZdorovieCurrent();
            lbValue.Text = value;
        }

        private void btnZver_Click(object sender, EventArgs e)
        {
            PersonajCfg personaj = cmbPersonaj.SelectedItem as PersonajCfg;
            string value = new PersonajInfo(personaj).GetZverCurrent();
            //int max = new PersonajInfo(personaj).GetZverMax();
            lbValue.Text = value;
        }

        private void cmbPersonaj_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtEmail.Text = CurrentPersonaj.Email;
            txtPassword.Text = CurrentPersonaj.Password;
        }

        #endregion Get Personaj Info


        private void btnCcSendBoat_Click(object sender, EventArgs e)
        {
            SendBoatChain ch = new SendBoatChain();
            ch.Personaj = new PersonajCfg();
            ch.Personaj["Name"] = txtEmail.Text;
            ch.Personaj["Password"] = txtPassword.Text;
            ch.RunChain();
            MessageBox.Show(ch.IsSuccessfulyInvoked.ToString().ToUpper());
        }









        private void btnCcTestWorkInKarier_Click(object sender, EventArgs e)
        {
            WorkInKarierChain ch = new WorkInKarierChain();
            ch.Personaj["Name"] = txtEmail.Text;
            ch.Personaj["Password"] = txtPassword.Text;
            ch.RunChain();
            MessageBox.Show(ch.IsSuccessfulyInvoked.ToString().ToUpper());
        }

        private void btnCcTestTryGetCristal_Click(object sender, EventArgs e)
        {
            TryGetCristalChain ch = new TryGetCristalChain();
            ch.Personaj["Name"] = txtEmail.Text;
            ch.Personaj["Password"] = txtPassword.Text;
            ch.RunChain();
            MessageBox.Show(ch.IsSuccessfulyInvoked.ToString().ToUpper());
        }

        private void btnDrinkZelenka_Click(object sender, EventArgs e)
        {
            DrinkZelenkaChain ch = new DrinkZelenkaChain();
            ch.Personaj["Name"] = txtEmail.Text;
            ch.Personaj["Password"] = txtPassword.Text;
            ch.RunChain();
            MessageBox.Show(ch.IsSuccessfulyInvoked.ToString().ToUpper());
        }

        private void btnDrinkSinka_Click(object sender, EventArgs e)
        {
            DrinkSinkaChain ch = new DrinkSinkaChain();
            ch.Personaj["Name"] = txtEmail.Text;
            ch.Personaj["Password"] = txtPassword.Text;
            ch.RunChain();
            MessageBox.Show(ch.IsSuccessfulyInvoked.ToString().ToUpper());
        }

        private void btnDrinkBoth_Click(object sender, EventArgs e)
        {
            bool ProcessFlag = true;

            try
            {
                LoginChain ch0 = new LoginChain();
                ch0.Personaj["Name"] = txtEmail.Text;
                ch0.Personaj["Password"] = txtPassword.Text;
                ch0.RunChain();
                ProcessFlag = ch0.IsSuccessfulyInvoked.Value;
                if (!ProcessFlag) throw new Exception();

                //DrinkZelenkaChain ch1 = new DrinkZelenkaChain(ch0.BotvaContext);
                //ch1.Name = txtEmail.Text;
                //ch1.Password = txtPassword.Text;
                //ch1.RunChain();
                //ProcessFlag = ch1.IsSuccessfulyInvoked.Value;
                //if (!ProcessFlag) throw new ProcessingFailedException();

                DrinkSinkaChain ch2 = new DrinkSinkaChain(ch0.Context);
                ch2.WithInheritedContext = true;
                //ch2.LastContent = ch0.LastContent;
                //ch2.Name = txtEmail.Text;
                //ch2.Password = txtPassword.Text;
                ch2.RunChain();
                ProcessFlag = ch2.IsSuccessfulyInvoked.Value;
                if (!ProcessFlag) throw new Exception();

                LogoutChain ch3 = new LogoutChain(ch2.Context);
                ch2.WithInheritedContext = true;
                //ch3.Name = txtEmail.Text;
                //ch3.Password = txtPassword.Text;
                ch3.RunChain();
                ProcessFlag = ch3.IsSuccessfulyInvoked.Value;
                if (!ProcessFlag) throw new Exception();
            }
            catch (Exception ex)
            {
                MessageBox.Show(false.ToString().ToUpper());
            }
            MessageBox.Show(true.ToString().ToUpper());
        }

        private void btnTestSendToBigAdventure_Click(object sender, EventArgs e)
        {
            //Expression exp = a => a + 1;
            //return;


            bool ProcessFlag = true;

            PersonajCfg personaj = cmbPersonaj.SelectedItem as PersonajCfg;

            try
            {
                LoginChain ch0 = new LoginChain();
                ch0.Personaj["Name"] = txtEmail.Text;
                ch0.Personaj["Password"] = txtPassword.Text;
                ch0.RunChain();
                ProcessFlag = ch0.IsSuccessfulyInvoked.Value;
                if (!ProcessFlag) throw new Exception();

                SendLetunToBigAdventureChain ch1 = new SendLetunToBigAdventureChain(ch0.Context);
                ch1.GildiaId = personaj.WarGildia.GildiaId;
                ch1.LetunId = personaj.WarGildia.LetunId;
                ch1.WithInheritedContext = true;
                ch1.RunChain();
                ProcessFlag = ch1.IsSuccessfulyInvoked.Value;
                if (!ProcessFlag) throw new Exception();

                LogoutChain ch2 = new LogoutChain(ch1.Context);
                ch2.WithInheritedContext = true;
                ch2.RunChain();
                ProcessFlag = ch2.IsSuccessfulyInvoked.Value;
                if (!ProcessFlag) throw new Exception();
            }
            catch (Exception ex)
            {
                MessageBox.Show(false.ToString().ToUpper());
            }
            MessageBox.Show(true.ToString().ToUpper());
        }

        private void btnTestBuyTools_Click(object sender, EventArgs e)
        {
            bool ProcessFlag = true;

            try
            {
                LoginChain ch0 = new LoginChain();
                ch0.Personaj["Name"] = txtEmail.Text;
                ch0.Personaj["Password"] = txtPassword.Text;
                ch0.RunChain();
                ProcessFlag = ch0.IsSuccessfulyInvoked.Value;
                if (!ProcessFlag) throw new Exception();

                BuyToolsChain ch1 = new BuyToolsChain(ch0.Context);
                ch1.WithInheritedContext = true;
                ch1.RunChain();
                ProcessFlag = ch1.IsSuccessfulyInvoked.Value;
                if (!ProcessFlag) throw new Exception();

                LogoutChain ch2 = new LogoutChain(ch1.Context);
                ch2.WithInheritedContext = true;
                ch2.RunChain();
                ProcessFlag = ch2.IsSuccessfulyInvoked.Value;
                if (!ProcessFlag) throw new Exception();
            }
            catch (Exception ex)
            {
                MessageBox.Show(false.ToString().ToUpper());
            }
            MessageBox.Show(true.ToString().ToUpper());
        }

        private void btnMonster_Click(object sender, EventArgs e)
        {
            bool ProcessFlag = true;

            try
            {
                FightWithMonsterChain ch0 = new FightWithMonsterChain();
                ch0.Personaj["Name"] = txtEmail.Text;
                ch0.Personaj["Password"] = txtPassword.Text;
                ch0.RunChain();
                ProcessFlag = ch0.IsSuccessfulyInvoked.Value;
            }
            catch (Exception ex)
            {
                MessageBox.Show(false.ToString().ToUpper());
            }

            MessageBox.Show(true.ToString().ToUpper());
        }

        private void btnPercent_Click(object sender, EventArgs e)
        {
            string content = FileHelper.GetContent(@"h:\- B -\шахта - попытка.html", Encoding.GetEncoding("windows-1251"));

            //"Вероятность успеха - 85 %."
            content = content
                .Replace(" ", string.Empty)
                .Replace("-", string.Empty)
                .Replace("%", string.Empty);
            string pattern = @"Вероятность успеха - (?<percent>[0-9]*) %\."
                .Replace(" ", string.Empty)
                .Replace("-", string.Empty)
                .Replace("%", string.Empty)
                .Replace("[09]", "[0-9]");
            Regex re = new Regex(pattern, RegexOptions.CultureInvariant);
            Match m = re.Match(content);
            if (m != null)
            {
                Group g = m.Groups["percent"];
                if (g != null)
                {
                    if (!StringHelper.IsnullOrBlank(g.Value))
                    {
                        int value = Int32.Parse(g.Value);
                        lbValue.Text = value.ToString();
                    }
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string content = FileHelper.GetContent(@"h:\- B -\personaj - index.html", Encoding.GetEncoding("windows-1251"));

            ////"Вероятность успеха - 85 %."
            //content = content
            //    .Replace(" ", string.Empty)
            //    .Replace("-", string.Empty)
            //    .Replace("%", string.Empty);
            //string pattern = @"Вероятность успеха - (?<percent>[0-9]*) %\."
            //    .Replace(" ", string.Empty)
            //    .Replace("-", string.Empty)
            //    .Replace("%", string.Empty)
            //    .Replace("[09]", "[0-9]");
            //Regex re = new Regex(pattern, RegexOptions.CultureInvariant);
            //Match m = re.Match(content);
            //if (m != null)
            //{
            //    Group g = m.Groups["percent"];
            //    if (g != null)
            //    {
            //        if (!StringHelper.IsnullOrBlank(g.Value))
            //        {
            //            int value = Int32.Parse(g.Value);
            //            lbValue.Text = value.ToString();
            //        }
            //    }
            //}

            HAP.HtmlDocument html = new HAP.HtmlDocument();
            html.OptionFixNestedTags = true;
            html.LoadHtml(content);

            HAP.HtmlNode node = html.DocumentNode.SelectSingleNode("//*[@id=\"potions\"]");
            HAP.HtmlNode ahrefNode = node.ChildNodes[1].ChildNodes[1].ChildNodes[0].ChildNodes[0].ChildNodes[1];
            //?drink=1&k=28691
            string href = ahrefNode.Attributes["href"].Value;

            UrlInfo ui = UrlParser.Parse(href);
            string k = ui.QueryArgs["k"].First();
            //string[] urlParts = href.Split('?');
            //string qs = urlParts[1];
            //string[] qsParts = qs.Split('&');
            //string k = string.Empty;
            //string kValue = string.Empty;
            //foreach (string qsPart in qsParts)
            //{
            //    string[] qsPartParts = qsPart.Split('=');
            //    string name = qsPartParts[0];
            //    if (name.Trim().ToUpper() == "k".ToUpper())
            //        kValue = qsPartParts[1];
            //}
        }

        private void txtLogForWorkInKarier_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button8_Click(object sender, EventArgs e)
        {
            PersonajCfg personaj = cmbPersonaj.SelectedItem as PersonajCfg;
            var info = new PersonajInfo(personaj).GetInfo();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnSaveTime_Click(object sender, EventArgs e)
        {
            PersonajInfo pi = new PersonajInfo(CurrentPersonaj);
            int time = (int)pi.GetSaveTime().TotalMilliseconds;
            TimeSpan ts = TimeSpan.FromMilliseconds(time);
            MessageBox.Show(ts.ToString());
        }




    }
}
